<?php

namespace App\Admin\Extensions;

use Encore\Admin\Grid;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;

class ExportWithTableName extends AbstractExporter
{
    protected $file_name = '';
    protected $keys = [];
    protected $key_maps = [];
    protected $title = [];
    protected $table_name;

    public function __construct($table_name, $file_name = 'File_name', $keys = ['id'], $key_maps = [], $title = [])
    {
        parent::__construct(null);
        $this->file_name = $file_name;
        $this->keys = $keys;
        $this->key_maps = $key_maps;
        $this->title = $title;
        $this->table_name = $table_name;
    }

    public function export()
    {
        $self = &$this;
        Excel::create($self->file_name, function ($excel) use (&$self) {

            $excel->sheet($self->file_name, function ($sheet) use (&$self) {

                $use_map = !empty($self->key_maps);
                $rows = collect($this->getData())->map(function ($item) use (&$self, &$use_map) {
                    $item = DB::table($self->table_name)->where('id', $item['id'])->select()->get()->all();
                    $item = (array)$item[0];
                    $row_filtered = array_only($item, $self->keys);
                    if($use_map){
                        foreach ($self->key_maps as $column => $maps){
                            if(isset($row_filtered[$column])){
                                $row_filtered[$column] = $maps[$row_filtered[$column]];
                            }
                        }
                    }
                    return $row_filtered;
                });

                if (!empty($self->title)) {
                    $rows->prepend($self->title);
                }
                $sheet->rows($rows);

            });

        })->export('xls');
    }
}